import { Component, OnInit } from '@angular/core';
import { TreeNode } from 'primeng/primeng';
import { FormDesignService } from './fb-design.service';
import { DialogService } from 'primeng/primeng';
import { Router, ActivatedRoute } from '@angular/router';
import { MdlSnackbarService } from '@angular-mdl/core';
import { FormAddComponent } from './baseinfo/fb-add.component';


@Component({
  templateUrl: './fb-design.component.html',
  styleUrls: ['./fb-design.component.scss'],
  providers: [FormDesignService, DialogService]
})
export class FormDesignComponent implements OnInit {

  selectedNode: TreeNode = {};
  formId: number = 0;
  formTree: TreeNode[];
  loading: boolean = true;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private dialogService: DialogService,
    private snackbarService: MdlSnackbarService,
    private formDesignService: FormDesignService) {
  }

  ngOnInit() {
    this.initFormTree(null);
    //监听子组件中添加或删除事件，刷新树控件列表
    this.formDesignService.routeMsgPush$.subscribe(data => this.initFormTree(data));
  }

  /**树节点选中 */
  nodeSelect() {
    this.formId = this.selectedNode['id'].replace('FORM_', '');
  }

  /** 初始化树 */
  initFormTree(formId: number) {
    this.formDesignService.getFormTree().subscribe(formTree => {
      this.loading = false;
      this.formTree = formTree
      this.selectedNode = null;
      if (formTree.length > 0) {
        let temp = formTree[0];
        while (temp.id.indexOf('FORM') < 0) {
          temp = temp.children[0];
        }
        this.selectedNode = temp;
        this.formId = this.selectedNode['id'].replace('FORM_', '');
      }
    });
  }



  /**新增表单 */
  formAdd($event) {
    const ref = this.dialogService.open(FormAddComponent, {
      header: '添加表单',
      width: '450px',
      contentStyle: { 'height': '280px' },
      data: {}
    });
    ref.onClose.subscribe(data => {
      if (data) {
        this.loading = true;
        this.initFormTree(data);
      }
    });
  }
}
